<?php

namespace app\bh\controller;

use app\bh\model\DataConfigModel;
use app\bh\model\DataModel;
use think\Controller;
use think\Error;
use think\Request;

class DataConfigController extends BaseAdminController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        $config = DataConfigModel::select();
        return $this->SuccessReturn('ok', $config);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //

    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $type = $request->post('type');
        $data_config = $request->post('config');
        //判断type
        $type_model = DataConfigModel::where('type', $type)->find();
        if ($type_model) return $this->ErrorReturn(400, '存在相同类别 请修改');
        $config = new DataConfigModel();
        $config->type = $type;
        $config->config = $data_config;
        $config->save();
        return $this->SuccessReturn('ok', $config);
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        $id = $request->put('id');
        $type = $request->put('type');
        $data_config = $request->put('config');
        if (!$id) {
            return $this->ErrorReturn(403, '缺少必要参数');
        }
        //
        $type_res = DataConfigModel::where('type', $type)->find();
        if ($type_res && $type_res->id != $id) return $this->ErrorReturn(400, '存在相同的类型');
        $config = DataConfigModel::find($id);
        if (!$config) return $this->ErrorReturn(400, '没找到参数类型');
        if ($type != '') $config->type = $type;
        if ($data_config != '') $config->config = $data_config;
        $config->save();
        return $this->SuccessReturn('ok', $config);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id, Request $request)
    {
        //
        $id = $request->post('id');
        if ($id == 0) return $this->ErrorReturn(400, '参数id无效');
        //查询是否存在此用户
        $data = DataConfigModel::where('id', $id)->find();
        if (!$data) return $this->ErrorReturn(404, '找不到此参数');
        $data->delete();
        return $this->SuccessReturn('删除成功');
    }
}
